import defaultSettings from '@/settings'
import { ThemeEnum } from '@/enums/ThemeEnum'
import Color from 'color'
export const useSettingsStore = defineStore('setting', () => {
    // state
    // 是否显示设置
    const settingsVisible = ref(false)
    // 是否开启水印
    const watermarkEnabled = useStorage<boolean>(
        'watermarkEnabled',
        defaultSettings.watermarkEnabled
    )
    // 主题：light-亮色(默认) dark-暗色
    const theme = useStorage<string>('theme', defaultSettings.theme)
    /**
     * 布局切换
     * 注意：为了演示，切换布局时，颜色会被还原成默认，代码位置：/@/layout/navBars/breadcrumb/setings.vue
     * 中的 `initSetLayoutChange(设置布局切换，重置主题样式)` 方法
     */
    // 布局切换：可选值"<defaults|classic|transverse|columns>"，默认 defaults
    const layout = useStorage<string>('layout', defaultSettings.layout)
    // 是否显示侧边栏logo
    const sidebarLogo = useStorage<boolean>(
        'sidebarLogo',
        defaultSettings.sidebarLogo
    )
    // 是否显示标签视图
    const tagsView = useStorage<boolean>('tagsView', defaultSettings.tagsView)
    // 是否固定头部
    const fixedHeader = useStorage<boolean>(
        'fixedHeader',
        defaultSettings.fixedHeader
    )
    // 主题颜色
    const themeColor = useStorage<string>(
        'themeColor',
        defaultSettings.themeColor
    )
    // action
    /**
     * 切换主题
     */
    function changeTheme(val: string) {
        theme.value = val
    }
    /**
     * 切换主题颜色
     *
     * @param color 主题颜色
     *
     */
    function changeThemeColor(color: string) {
        themeColor.value = color
    }
    // 生命周期
    watch(
        [theme, themeColor],
        ([newTheme, newThemeColor], [oldTheme, oldThemeColor]) => {
            if (newTheme !== oldTheme) {
                if (newTheme === ThemeEnum.DARK) {
                    document.documentElement.classList.add('dark')
                } else {
                    document.documentElement.classList.remove('dark')
                }
            }

            if (newThemeColor !== oldThemeColor) {
                const rootStyle = document.documentElement.style
                rootStyle.setProperty(`--el-color-primary`, newThemeColor)
                rootStyle.setProperty(
                    `--el-color-primary-dark-2`,
                    newThemeColor
                )

                for (let i = 1; i < 10; i++) {
                    rootStyle.setProperty(
                        `--el-color-primary-light-${i}`,
                        `${Color(newThemeColor).alpha(1 - i * 0.1)}`
                    )
                }
            }
        },
        {
            immediate: true, // 立即执行，确保在侦听器创建时执行一次
        }
    )
    /**
     * 切换布局
     */
    function changeLayout(val: string) {
        layout.value = val
    }
    return {
        watermarkEnabled,
        theme,
        changeTheme,
        layout,
        sidebarLogo,
        settingsVisible,
        tagsView,
        fixedHeader,
        themeColor,
        changeThemeColor,
        changeLayout,
    }
})
